class Solution {
public:
    vector<int> father;
    int find(int x){
        return x == father[x] ? x : find(father[x]);
    }
    bool check(const string& s1,const string& s2){
        int n = 0;
        int m = s1.size();
        for(int i = 0;i < m;i++){
            if(s1[i] != s2[i]){
                n++;
            }
            if(n > 2){
                return false;
            }
        }
        return true;
    }
    
    int numSimilarGroups(vector<string>& strs) {
        if(strs.size() == 0) return 0;
        if(strs.size() == 1) return 1;

        int n = strs.size();
        father.resize(n);
        for(int i = 0;i < n;i++){
            father[i] = i;
        }
        
        for(int i = 0;i < n;i++){
            for(int j = i + 1;j < n;j++){
                int x = find(i);
                int y = find(j);
                if(x == y) continue;
                if(check(strs[i],strs[j])){
                    father[y] = x;
                }
            }
        }

        
        int ret = 0;
        for(int i = 0;i < n;i++){
            if(father[i] == i){
                ret++;
            }
        }
        return ret;
    }
};
